package com.ljy.jymail.order.config;

import com.sun.org.apache.bcel.internal.generic.NEW;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.annotation.PostConstruct;

@Configuration
public class MyRabbitConfig {

//    @Autowired
    RabbitTemplate rabbitTemplate;
//    public MyRabbitConfig(RabbitTemplate rabbitTemplate){
//        this.rabbitTemplate=rabbitTemplate;
//        initRabbitplate();
//    }

    @Bean
    @Primary
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory){
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        this.rabbitTemplate = rabbitTemplate;
        rabbitTemplate.setMessageConverter(messageConverter());
        initRabbitplate();
        return rabbitTemplate;
    }

    /*使发送的消息转换为json格式*/
    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    /*
    * 定制rabbitTemplate
    * 1.服务器收到消息回调 RabbitTemplate.ConfirmCallback()
    * 2.消息正确抵达队列回调：
    *   publisher-returns:true
    *   template.mandatory:true
    * */
//    @PostConstruct
    public void initRabbitplate(){
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {

            //触发时机：服务端成功发送消息
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                //correlationData：当前消息的唯一关联数据，消息的唯一Id
                //ack 消息是否成功受奥
                //cause 失败的原因


                /*
                * 做好消息确认机制(Consume【手动ack】,publisher)
                * 每一个发送的消息都在数据库做好记录，定期把失败的消息进行重新发送
                *
                * */
                //服务器收到了消息
                //TODO：消息写入数据库,记录消息发送日志

            }
        });

        //触发时机:只要消息没有投递给指定的队列，就出发这个投递失败的回调
        rabbitTemplate.setReturnsCallback(new RabbitTemplate.ReturnsCallback() {
            /*
            * returnedMessage
            *   Message message 失败的详细信息
            *   int replyCode 回复的状态码
            *   String replyText 回复的文本内容
            *   String exchange 发送的交换机
            *   String routingKey 使用的路由键
            * */

            @Override
            public void returnedMessage(ReturnedMessage returnedMessage) {

                //报错来到此方法，TODO  消息写入数据库,记录消息错误码

            }
        });
    }
}
